<?php

namespace app\index\middleware;

use Closure;
use service\JwtService;
use service\NodeService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Cache;
use think\Request;

/**
 * 系统权限访问管理
 * Class Auth
 * @package app\admin\middleware
 */
class Auth{

    private $need_login_node = [
            'index/member/get_member_info',
        ];


    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public
    function handle($request, Closure $next){

        list($module, $controller, $action) = [$request->module(), $request->controller(), $request->action()];
        $node        = NodeService::parseNodeStr("{$module}/{$controller}/{$action}");
        $access_auth = $this->build_access_auth($node);
        $access_token = $request->header('access-token');
        $logined       = false;
        $encodeData    = '';
        if($access_token){
            $encodeData  = JwtService::decodeToken($access_token);
            if(!isError($encodeData)){
                $member = Cache::get('member:info:'.$encodeData->data->id);
                if($member){
                    setCurrentMember($member);
                    $logined = true;
                }
            }
        }
        // 登录状态检查
        if($access_auth['need_login']){
            if(isError($encodeData)){
                //TODO 启用refreshToken
                if($encodeData['errno']==3){
                    $msg = ['code' => 4010, 'msg' => 'accessToken过期'];
                    return json($msg);
                }
                $msg = ['code' => 4010, 'msg' => '登录超时，请重新登录'];
                return json($msg);
            }
            if(!$logined){
                $msg = ['code' => 4010, 'msg' => '登录超时，请重新登录'];
                return json($msg);
            }
        }

        return $next($request);
    }

    /**
     * 根据节点获取对应权限配置
     * @param string $node 权限节点
     * @return array
     */
    private
    function build_access_auth($node){
        return [
            'need_login' => in_array($node, $this->need_login_node),
        ];
    }
}
